/**
 * 学习数据管理类
 * 负责管理用户的学习数据，如学习次数、最后学习时间、记忆状态等
 */
// 提供单例模式的学习数据管理器
let instance = null;

// 导入存储管理器
const storageManager = require('./storageManager').getInstance();
class WordLearningDataManager {
  constructor() {
    // 使用storageManager.STORAGE_KEYS中的常量，不再在构造函数中定义STORAGE_KEY
  }
  
  /**
   * 获取学习数据管理器的单例实例
   * @returns {WordLearningDataManager} 学习数据管理器实例
   */
  static getInstance() {
    if (!instance) {
      instance = new WordLearningDataManager();
    }
    return instance;
  }

  /**
   * 获取所有学习数据
   * @returns {Object} 学习数据字典 {wordId: learningInfo}
   */
  getAllLearningData() {
    const learningData = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_LEARNING_INFO_DATA) || {};
    return learningData;
  }

  /**
   * 保存所有学习数据
   * @private
   * @param {Object} learningData - 学习数据字典
   */
  _saveAllLearningData(learningData) {
    storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_LEARNING_INFO_DATA, learningData);
  }

  /**
   * 获取指定单词的学习数据
   * @param {string} wordId - 单词ID
   * @returns {Object} 学习数据对象
   */
  getLearningData(wordId) {
    const learningData = this.getAllLearningData();
    return learningData[wordId] || {
      lastLearnTime: null,
      learnCount: 0,
      memorized: false
    };
  }

  /**
   * 更新指定单词的学习数据
   * @param {string} wordId - 单词ID
   * @param {Object} updateData - 更新数据
   * @returns {boolean} 是否更新成功
   */
  updateLearningData(wordId, updateData) {
    const learningData = this.getAllLearningData();
    const currentData = this.getLearningData(wordId);
    
    // 合并更新数据
    learningData[wordId] = {
      ...currentData,
      ...updateData
    };
    
    this._saveAllLearningData(learningData);
    return true;
  }

  /**
   * 增加单词的学习次数
   * @param {string} wordId - 单词ID
   * @returns {number} 更新后的学习次数
   */
  incrementWordLearnCount(wordId) {
    const learningInfo = this.getLearningData(wordId);
    const newCount = (learningInfo.learnCount || 0) + 1;
    
    this.updateLearningData(wordId, {
      learnCount: newCount,
      lastLearnTime: new Date().toISOString()
    });
    
    return newCount;
  }

  /**
   * 设置单词的记忆状态
   * @param {string} wordId - 单词ID
   * @param {boolean} isMemorized - 是否记住
   * @returns {boolean} 是否设置成功
   */
  setWordMemorizedStatus(wordId, isMemorized) {
    return this.updateLearningData(wordId, {
      memorized: isMemorized
    });
  }

  /**
   * 批量设置单词的记忆状态
   * @param {Array} wordIds - 单词ID数组
   * @param {boolean} isMemorized - 是否记住
   * @returns {boolean} 是否设置成功
   */
  batchSetWordsMemorizedStatus(wordIds, isMemorized) {
    const learningData = this.getAllLearningData();
    let updated = false;
    
    wordIds.forEach(wordId => {
      const currentData = learningData[wordId] || {
        lastLearnTime: null,
        learnCount: 0,
        memorized: false
      };
      
      learningData[wordId] = {
        ...currentData,
        memorized: isMemorized
      };
      updated = true;
    });
    
    if (updated) {
      this._saveAllLearningData(learningData);
    }
    
    return updated;
  }

  /**
   * 获取单词的学习状态
   * @param {string} wordId - 单词ID
   * @returns {boolean} 学习状态，通过learnCount>0判断，默认返回false（未学过）
   */
  getWordLearnedStatus(wordId) {
    const learningInfo = this.getLearningData(wordId);
    return (learningInfo.learnCount || 0) > 0;
  }

  /**
   * 获取单词的学习次数
   * @param {string} wordId - 单词ID
   * @returns {number} 学习次数，默认返回0
   */
  getWordLearnCount(wordId) {
    const learningInfo = this.getLearningData(wordId);
    return learningInfo.learnCount || 0;
  }

  /**
   * 获取单词的最后学习时间
   * @param {string} wordId - 单词ID
   * @returns {string|null} 最后学习时间，默认返回null
   */
  getWordLastLearnTime(wordId) {
    const learningInfo = this.getLearningData(wordId);
    return learningInfo.lastLearnTime || null;
  }

  /**
   * 获取单词的记忆状态
   * @param {string} wordId - 单词ID
   * @returns {boolean} 记忆状态，默认返回false（未记住）
   */
  getWordMemorizedStatus(wordId) {
    const learningInfo = this.getLearningData(wordId);
    return learningInfo.memorized || false;
  }

  /**
   * 初始化从旧版数据迁移
   * 将wordDictionary中的learningInfo数据迁移到新的学习数据存储中
   * @param {Object} words - 单词数据对象，键为wordId，值为单词对象
   */
  migrateFromOldData(words) {
    try {
      // 接收words作为参数，避免创建循环依赖
      if (!words) {
        return { success: true, migrated: false };
      }
      
      const existingLearningData = this.getAllLearningData();
      let hasChanges = false;
      
      // 遍历所有单词，迁移learningInfo数据
      Object.keys(words).forEach(wordId => {
        const word = words[wordId];
        if (word.learningInfo && !existingLearningData[wordId]) {
          // 只迁移还没有在新存储中的数据
          existingLearningData[wordId] = word.learningInfo;
          hasChanges = true;
        }
        // 从单词数据中移除learningInfo字段
        if (word.learningInfo) {
          delete word.learningInfo;
          hasChanges = true;
        }
      });
      
      // 如果有变化，保存更新后的数据
      if (hasChanges) {
        this._saveAllLearningData(existingLearningData);
      }
      
      return { success: true, migrated: hasChanges };
    } catch (error) {
      console.error('迁移学习数据失败:', error);
      return { success: false, message: error.message };
    }
  }
}

// 导出类和单例实例
module.exports = {
  WordLearningDataManager,
  getInstance: WordLearningDataManager.getInstance,
  getWordLearningDataManager: WordLearningDataManager.getInstance,
  instance: WordLearningDataManager.getInstance()
};

// 同时设置默认导出为单例实例
module.exports.default = WordLearningDataManager.getInstance();